import java.net.*;
import javax.swing.*;

import org.python.core.*;
import org.python.util.*;

import enigma.shells.jython.*;

public class AppletConsole extends JApplet {
	Thread runner;
	JythonShell shell;
	
	public void init() {
		PySystemState.initialize();
		PySystemState.add_classdir(System.getProperty("java.home") + java.io.File.separatorChar + "lib");

		PySystemState.add_package("org.python");
		PySystemState.add_package("org.python.core");
		PySystemState.add_package("org.python.util");
		
		PySystemState.add_package("enigma");
		PySystemState.add_package("enigma.shells");
		PySystemState.add_package("enigma.shells.jython");
		
		JavaLibLoader jLoader = new JavaLibLoader();
		PythonLibLoader pLoader = new PythonLibLoader();
		
		try {
			String extpath = getParameter("python.extpath");
			if (extpath != null) {
				String [] urls = getURLPaths(extpath);
				for (int i = 0; i < urls.length; i++) {
					jLoader.load(new URL(urls[i]));
				}
			}
			
			String pythonpath = getParameter("python.path");
			if (pythonpath != null) {
				String [] urls = getURLPaths(pythonpath);
				for (int i = 0; i < urls.length; i++) {
					pLoader.load(new URL(urls[i]));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		shell = new JythonShell();
		add(shell);
	}
	
	public void start() {
		runner = new Thread(shell);
		runner.start();
	}
	
	public String[] getURLPaths(String path) {
		String[] URLs = path.split(":");
		URL dirURL = AppletConsole.class.getResource("./");
		
		for (int i = 0; i < URLs.length; i++) {
			String thisURL = URLs[i].trim();
			
			try {
				thisURL = URLDecoder.decode(thisURL, "utf-8");
				thisURL = new URL(thisURL).toString();
			} catch (Exception e) {
				thisURL = getCodeBase() + thisURL;
			}
			
			URLs[i] = thisURL;
		}
		
		return URLs;
	}
}
